package com.kexio.common.page;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.kexio.common.dto.PageResponse;

/**
 * 分页对象转换器（对 ORM 去耦）。
 */
public final class PageConverters {
    private PageConverters() {}

    public interface Slice<T> {
        List<T> getRecords();
        long getTotal();
        long getCurrent();
        long getSize();
    }

    public static <T> PageResponse<T> toResponse(Slice<T> page) {
        if (page == null) {
            return PageResponse.empty();
        }
        return PageResponse.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    public static <S, T> List<T> mapList(List<S> source, Function<S, T> mapper) {
        if (source == null || source.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return source.stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
    }

    public static <S, T> PageResponse<T> map(List<S> records,
                                             long total,
                                             long current,
                                             long size,
                                             Function<S, T> mapper) {
        List<T> mapped = mapList(records, mapper);
        return PageResponse.of(mapped, total, current, size);
    }
}


